package com.example.hdz.testfileexplorer;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author hdz
 */

//https://blog.csdn.net/Rookie_or_beginner/article/details/55506289
//https://blog.csdn.net/xialong_927/article/details/81902793
//https://blog.csdn.net/ABC__D/article/details/51790806



public class MainActivity extends AppCompatActivity {

    public static final String TAG = "Test";

    private TextView mTextView;
    private ImageView mSrcImg;
    private ImageView mDstImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mSrcImg = (ImageView)findViewById(R.id.srcImg);
        mDstImg = (ImageView)findViewById(R.id.dstImg);
        mTextView = (TextView)findViewById(R.id.text);
        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openFileExplorer();
            }
        });
    }



    private void openFileExplorer() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //如果大于等于7.0使用
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivityForResult(intent, 8);
        } else {
            startActivityForResult(intent, 8);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 8) {
                Uri uri = data.getData();
                String path = GetImgPath.getPath(this, uri);
                mTextView.setText(path);

                // 原图显示
                Bitmap bitmap= BitmapFactory.decodeFile(path);
                mSrcImg.setImageBitmap(bitmap);
                //Log.e("test", bitmap.getByteCount()+"");
                //Log.e("test", bitmap.getWidth()+"x"+bitmap.getHeight());

                // 压缩后显示
                //Bitmap tmpBmp = getSmallBitmap(path);
                //mDstImg.setImageBitmap(tmpBmp);
                //Log.e("test", tmpBmp.getByteCount()+"");
                //Log.e("test", tmpBmp.getWidth()+"x"+tmpBmp.getHeight());
                //Log.e("test", saveMyBitmap("test", tmpBmp));

                //Log.e("test", saveMyBitmap("test", getYaSuoBitmapFromImagePath(path, 256, 256)));

                //Log.e("test", saveMyBitmap("test", setImgSize(bitmap, 256,256)));
                //Log.e("test", saveMyBitmap("test", getYaSuoBitmapFromImagePath(path, 256,256)));

                //Uri destinationUri = Uri.fromFile(new File(getCacheDir(), System.currentTimeMillis() + ".jpg"));
                Uri destinationUri = Uri.fromFile(new File("/sdcard/", System.currentTimeMillis() + ".png"));
                /*UCrop.of(uri, destinationUri)
                        .withAspectRatio(1, 1)
                        .withMaxResultSize(256, 256)
                        .start(this);*/

                UCrop uCrop = UCrop.of(uri, destinationUri);
                //初始化UCrop配置
                UCrop.Options options = new UCrop.Options();
                //设置裁剪图片可操作的手势
                options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
                //设置toolbar颜色
                options.setToolbarColor(ActivityCompat.getColor(this, R.color.colorPrimary));
                //设置状态栏颜色
                options.setStatusBarColor(ActivityCompat.getColor(this, R.color.colorPrimary));
                //是否隐藏底部工具，默认显示
                options.setHideBottomControls(false);
                //是否能调整裁剪框
                options.setFreeStyleCropEnabled(false);
                //设置裁剪出来的图片为PNG格式
                options.setCompressionFormat(Bitmap.CompressFormat.PNG);
                //是否显示裁剪边框
                options.setShowCropFrame(true);
                //是否显示裁剪网格线
                options.setShowCropGrid(true);
                //设置标题
                options.setToolbarTitle("uCrop裁剪图片");
                //设置图片压缩质量
                options.setCompressionQuality(100);
                //设置裁剪框之外的颜色
                options.setDimmedLayerColor(Color.MAGENTA);
                //是否为圆形裁剪框，默认false
                options.setCircleDimmedLayer(false);
                // 一共三个参数，分别对应裁剪功能页面的“缩放”，“旋转”，“裁剪”界面，
                // 对应的传入NONE，就表示关闭了其手势操作，比如这里我关闭了缩放和旋转界面的手势，只留了裁剪页面的手势操作
                options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
                //配置参数
                uCrop.withOptions(options);
                //设置裁剪宽高比例为1:1
                uCrop.withAspectRatio(1, 1);
                //裁剪后的图片分辨率
                uCrop.withMaxResultSize(256, 256);
                uCrop.start(this);
            } else if (requestCode == UCrop.REQUEST_CROP) {
                final Uri resultUri = UCrop.getOutput(data);
                Bitmap bitmap= BitmapFactory.decodeFile(resultUri.getPath());
                mDstImg.setImageBitmap(bitmap);
                saveMyBitmap("test", bitmap);
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            final Throwable cropError = UCrop.getError(data);
        }
    }


    /**
     * 按比例缩放图片
     * @param path 图片地址
     * @return 返回Bitmap对象
     */
    public Bitmap getSmallBitmap(String path){
        //new 出来一个bitmap的参数
        BitmapFactory.Options options = new BitmapFactory.Options();
        //设置为true，不会生成Bitmap对象，只是读取尺寸和类型信息
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        //得到这个比例   并赋予option里面的inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 256, 256);
        //设置为false，即将要生成bitmap对象啦
        options.inJustDecodeBounds = false;
        //有了这个option，我们可以生成bitmap对象了
        return BitmapFactory.decodeFile(path, options);
    }
    public int calculateInSampleSize(BitmapFactory.Options options, int reqHeight, int reqWidth){
        //得到原始图片宽高
        int height = options.outHeight;
        int width = options.outWidth;
        //默认设置为1，即不缩放
        int inSampleSize=1;
        //如果图片原始的高大于我们期望的高，或者图片的原始宽大于我们期望的宽，换句话意思就是，我们想让它变小一点
        if (height > reqHeight || width > reqWidth) {
            //原始的高除以期望的高，得到一个比例
            final int heightRatio = Math.round((float) height/ (float) reqHeight);
            //原始的宽除以期望的宽，得到一个比例
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            //取上面两个比例中小的一个，返回这个比例
            inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
        }
        return inSampleSize;
    }


    public Bitmap setImgSize(Bitmap bm, int newWidth ,int newHeight){
        // 获得图片的宽高.
        int srcWidth = bm.getWidth();
        int srcHeight = bm.getHeight();
        Log.d(TAG, "srcWidth = " + srcWidth + ", srcHeight = " + srcHeight);

        int dstWidth = newWidth;
        int dstHeight = newHeight;
        if (srcWidth > srcHeight) {
            dstHeight = Math.round(((float) srcHeight)/srcWidth*newWidth);
        } else {
            dstWidth = Math.round(((float) srcWidth)/srcHeight*newHeight);
        }

        Log.d(TAG, "tmpWidth = " + dstWidth + ", tmpHeight = " + dstHeight);

        // 计算缩放比例.
        float scaleWidth = ((float) dstWidth) / srcWidth;
        float scaleHeight = ((float) dstHeight) / srcHeight;

        // 取得想要缩放的matrix参数.
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片.
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, srcWidth, srcHeight, matrix, true);
        return newbm;
    }


    /**
     * 保存Bitmap到文件
     * @param bitName 文件名
     * @param mBitmap Bitmap对象
     * @return 返回保存的文件路径
     */
    public static String saveMyBitmap(String bitName, Bitmap mBitmap) {
        File f = new File("/sdcard/" + bitName + ".png");

        try {
            f.createNewFile();
        } catch (IOException e) {
            System.out.println("在保存图片时出错：" + e.toString());
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        } catch (Exception e) {
            return "create_bitmap_error";
        }
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "/sdcard/" + bitName + ".png";
    }




    public static Bitmap getYaSuoBitmapFromImagePath(String path, int targetW, int targetH) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = calculateInSampleSize(options);
        options.inSampleSize = inSampleSize;
        options.inJustDecodeBounds = false;
        Bitmap src = BitmapFactory.decodeFile(path, options);

        if (src == null) {
            return null;
        }
        Bitmap bitmap = null;

        if (targetH == 0 || targetW == 0) {
            bitmap = Bitmap.createScaledBitmap(src, width / inSampleSize, height / inSampleSize, false);
        } else {
            bitmap = Bitmap.createScaledBitmap(src, targetW, targetH, false);
        }

        if (src != bitmap) {
            src.recycle();
        }

        return bitmap;
    }

    /**
     * 计算压缩比
     *
     * @param options
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options) {
        int height = options.outHeight;
        int width = options.outWidth;

        int min = height > width ? width : height;
        int inSampleSize = min / 400;

        if (inSampleSize == 0)

            return 1;

        return inSampleSize;
    }
}
